package edu.xidian.cnmano.service.impl;

import edu.xidian.cnmano.dao.DeploymentInfoMapper;
import edu.xidian.cnmano.entities.monitor.DeploymentInfo;
import edu.xidian.cnmano.entities.monitor.DeploymentInfoExample;
import edu.xidian.cnmano.service.DeploymentInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

/**
 * Deployment相关的Service,主要用于DeploymentInfo的增删改查
 */
@Slf4j
@Service
public class DeploymentInfoServiceImpl implements DeploymentInfoService {

    @Resource
    private DeploymentInfoMapper mapper;

    @Override
    public DeploymentInfo getDeploymentInfoById(int id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public DeploymentInfo getDeploymentInfoByDeploymentNameAndNamespace(String deploymentName,String namespace) {
        DeploymentInfoExample example = new DeploymentInfoExample();
        example.createCriteria().andDeploymentNameEqualTo(deploymentName).andNamespaceEqualTo(namespace);
        List<DeploymentInfo> deploymentInfos = mapper.selectByExample(example);
        if(deploymentInfos==null || deploymentInfos.isEmpty()){
            return null;
        }else {
            return deploymentInfos.get(0);
        }
    }

    @Override
    public List<DeploymentInfo> listAllDeploymentInfo() {
        DeploymentInfoExample example = new DeploymentInfoExample();
        List<DeploymentInfo> deploymentInfos = mapper.selectByExample(example);
        deploymentInfos.sort(Comparator.comparing(DeploymentInfo::getNamespace));
        return deploymentInfos;
    }

    @Override
    public int updateDeploymentInfo(DeploymentInfo deploymentInfo) {
        try {
            DeploymentInfoExample example = new DeploymentInfoExample();
            example.createCriteria().andDeploymentNameEqualTo(deploymentInfo.getDeploymentName()).andNamespaceEqualTo(deploymentInfo.getNamespace());
            return mapper.updateByExampleSelective(deploymentInfo,example);
        }catch (Exception e){
            log.error(e.getMessage());
            return 0;
        }
    }

    @Override
    public int insertDeploymentInfo(DeploymentInfo deploymentInfo) {
        try {
            return mapper.insert(deploymentInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return 0;
        }
    }

    @Override
    public int deleteDeploymentInfo(DeploymentInfo deploymentInfo) {
        try {
            DeploymentInfoExample example = new DeploymentInfoExample();
            example.createCriteria().andDeploymentNameEqualTo(deploymentInfo.getDeploymentName()).andNamespaceEqualTo(deploymentInfo.getNamespace());
            return mapper.deleteByExample(example);
        }catch (Exception e){
            log.error(e.getMessage());
            return 0;
        }
    }
}
